{% extends "base.html" %}

{% block content %}
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h2>需求详情: {{ classification.req_id }}</h2>
        <div>
            <a href="{{ url_for('requirements.kanban') }}" class="btn btn-outline-primary">
                <i class="bi bi-kanban"></i> 返回看板
            </a>
            <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
                <i class="bi bi-trash"></i> 删除需求
            </button>
        </div>
    </div>

<div class="card mt-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">相关图表</h5>
        <div class="btn-group">
            <button class="btn btn-sm btn-primary dropdown-toggle" type="button" 
                    data-bs-toggle="dropdown" aria-expanded="false">
                <i class="bi bi-plus-lg"></i> 新建图表
            </button>
            <ul class="dropdown-menu">
                <li><a class="dropdown-item" href="#" onclick="createDiagram('erd')">实体关系图</a></li>
                <li><a class="dropdown-item" href="#" onclick="createDiagram('sequence')">时序交互图</a></li>
                <li><a class="dropdown-item" href="#" onclick="createDiagram('flowchart')">业务流程图</a></li>
            </ul>
        </div>
    </div>
    <div class="card-body">
        {% if classification.diagrams %}
            <div class="row">
                {% for diagram in classification.diagrams %}
                <div class="col-md-4 mb-3">
                    <div class="card h-100">
                        <div class="card-body">
                            <h6 class="card-title">{{ diagram.title }}</h6>
                            <div class="text-center">
                                {% set preview_code = diagram.mermaid_code | truncate(100) %}
                                <div class="mermaid">
                                    {{ preview_code }}
                                </div>
                            </div>
                        </div>
                        <div class="card-footer">
                            <small class="text-muted">
                                更新于 {{ diagram.updated_at.strftime('%Y-%m-%d %H:%M') }}
                            </small>
                            <div class="float-end">
                                <a href="{{ url_for('diagram.edit_diagram', diagram_id=diagram.id) }}" 
                                   target="_blank" class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                <button class="btn btn-sm btn-outline-danger" 
                                        onclick="deleteDiagram('{{ diagram.id }}')">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                {% endfor %}
            </div>
        {% else %}
            <div class="text-center py-4 text-muted">
                暂无相关图表，点击"新建图表"按钮创建
            </div>
        {% endif %}
    </div>
</div>

<script>
    function createDiagram(type) {
        const reqId = "{{ classification.req_id }}";
        const url = "{{ url_for('diagram.create_diagram', req_id='') }}" + reqId + "?type=" + type;
        window.open(url, "mermaidEditor", "width=1200,height=800,scrollbars=yes");
    }
    
    function deleteDiagram(diagramId) {
        if (confirm('确定删除此图表？')) {
            fetch("{{ url_for('diagram.delete_diagram', diagram_id=0) }}".replace('0', diagramId), {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    location.reload();
                }
            });
        }
    }
    
    // 初始化预览图
    mermaid.initialize({ startOnLoad: true, theme: 'neutral' });
    
    // 存储初始数据
    const initData = {
        id: (function() {
            try {
                return JSON.parse("{{ diagram.id if diagram else 'null' }}");
            } catch (e) {
                return undefined;
            }
        })(),
        req_id: "{{ classification.req_id }}",
        type: "{{ diagram_type }}",
        title: "{{ diagram.title if diagram else '' }}",
        mermaid_code: "{{ diagram.mermaid_code if diagram else '' }}",
    };

    // 初始化编辑器
    const editor = ace.edit("code-editor");
    editor.setTheme("ace/theme/monokai");
    editor.session.setMode("ace/mode/mermaid");
    editor.setOptions({
        fontSize: "14px",
        showLineNumbers: true,
        vScrollBarAlwaysVisible: true,
        highlightActiveLine: true,
        tabSize: 4,
        useSoftTabs: true,
    });

    // 设置初始值
    if (initData.mermaid_code) {
        editor.setValue(initData.mermaid_code, 1);
    }

    // 保存按钮
    document.getElementById("save-button").addEventListener("click", function() {
        const data = {
            id: initData.id,
            req_id: initData.req_id,
            type: initData.type,
            title: document.getElementById("title-input").value,
            mermaid_code: editor.getValue(),
        };

        fetch("{{ url_for('diagram.save_diagram') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                location.href = "{{ url_for('requirements.detail', req_id=classification.req_id) }}";
            }
        });
    });

    // 取消按钮
    document.getElementById("cancel-button").addEventListener("click", function() {
        location.href = "{{ url_for('requirements.detail', req_id=classification.req_id) }}";
    });

</script>    
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">
            <h4>基本信息</h4>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <p><strong>业务路径:</strong> {{ classification.full_path }}</p>
                    <p><strong>需求类型:</strong> {{ classification.req_type.name }}</p>
                    <p><strong>价值指标:</strong> {{ classification.value_metric }}</p>
                    <p><strong>影响维度:</strong> {{ classification.impact_dimensions }}</p>
                </div>
                <div class="col-md-6">
                    <p><strong>状态:</strong> <span class="badge bg-{{ 
                        'success' if pool.status == '业务闭环' 
                        else 'primary' if pool.status in ['开发', '测试'] 
                        else 'warning' if pool.status in ['审批', '评估中'] 
                        else 'secondary' 
                    }}">{{ pool.status }}</span></p>
                    <p><strong>优先级:</strong> <span class="badge bg-{{ 
                        'danger' if pool.priority > 8 
                        else 'warning' if pool.priority > 5 
                        else 'success' 
                    }}">P{{ pool.priority }}</span></p>
                    <p><strong>提出时间:</strong> {{ pool.request_time.strftime('%Y-%m-%d %H:%M') }}</p>
                    <p><strong>期望解决时间:</strong> {{ pool.expected_solve_time.strftime('%Y-%m-%d %H:%M') }}</p>
                </div>
            </div>
        </div>
    </div>
    
    <div class="card mb-4">
        <div class="card-header bg-info text-white">
            <h4>需求描述</h4>
        </div>
        <div class="card-body">
            <p>{{ pool.description }}</p>
        </div>
    </div>
    
    <div class="card">
        <div class="card-header bg-success text-white">
            <h4>解决方案</h4>
        </div>
        <div class="card-body">
            {% if pool.solution %}
                <p>{{ pool.solution }}</p>
                <p><strong>负责人:</strong> {{ pool.solution_owner }}</p>
            {% else %}
                <div class="alert alert-warning">
                    暂无解决方案
                </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除需求</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除需求 <strong>{{ classification.req_id }}</strong> 吗？此操作不可恢复！</p>
                <p class="text-danger"><strong>警告：</strong> 所有相关数据将被永久删除</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <form action="{{ url_for('requirements.delete_requirement', req_id=classification.req_id) }}" method="POST">
                    <button type="submit" class="btn btn-danger">确认删除</button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}